﻿using System;
using System.Text;

namespace AllInOnePluginBL.Helpers
{
    /// <summary>
    /// Summary description for VideoDetails
    /// </summary>
    public class VideoDetails
    {
        public string ErrorText { get; set; }
        public string Runtime { get; set; }
        public string Size { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public string Description { get; set; }
        public bool IsValid { get; set; }

        public override string ToString()
        {
            return CreateInfo(Name);
        }

        public string CreateInfo(string name)
        {
            var builder = new StringBuilder();

            if (!string.IsNullOrEmpty(name))
                builder.AppendFormat("{0} - ", name);

            if (!string.IsNullOrEmpty(Size))
                builder.AppendFormat("[{0}MB] ", ConvertBytesToMegabytes(Size));

            if (!string.IsNullOrEmpty(Runtime))
                builder.AppendFormat("[{0}] ", ConvertRuntime(Runtime));

            return builder.ToString();
        }

        private string ConvertRuntime(string runtime)
        {
            try
            {
                var splitedTime = runtime.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                if (splitedTime.Length != 2) return runtime;

                var newRuntime = TimeSpan.FromMinutes(double.Parse(splitedTime[0]));
                newRuntime = newRuntime.Add(TimeSpan.FromSeconds(double.Parse(splitedTime[1])));
                return newRuntime.ToString();
            }
            catch
            {
                return runtime;
            }
        }

        private int ConvertBytesToMegabytes(string bytes)
        {
            long convertedBytes;
            long.TryParse(bytes, out convertedBytes);
            if (convertedBytes == 0) return (int)convertedBytes;

            return (int)((convertedBytes / 1024f) / 1024f);
        }
    }
}